package com.chuhe.common.aspect;

import com.chuhe.common.annotation.GlobalInterceptor;
import com.chuhe.common.domain.dto.TokenUserInfoDto;
import com.chuhe.common.exception.CommonErrorEnum;
import com.chuhe.common.utils.AssertUtil;
import com.chuhe.common.utils.RedisComponet;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 全局拦截器
 * @Author: 楚河
 * @Date: 2025年05月12日21:20
 */
@Aspect
@Component
@Slf4j
public class GlobalOperationAspect {
    @Autowired
    private RedisComponet redisComponet;

    @Before("@annotation(com.chuhe.common.annotation.GlobalInterceptor)")
    public void interceptorDo(JoinPoint point){
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        GlobalInterceptor interceptor = method.getAnnotation(GlobalInterceptor.class);
        if(interceptor == null){
            return;
        }
        if(interceptor.checkLogin() || interceptor.checkAdmin()){
            checkLogin(interceptor.checkAdmin());
        }
    }

    /**
     * 校验登录
     * @Author: 楚河
     * @Date: 2025-05-12 21:28
     */
    private void checkLogin(boolean checkAdmin) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        TokenUserInfoDto infoDto = redisComponet.getTokenUserInfoByToken(request);
        AssertUtil.isEmpty(infoDto, CommonErrorEnum.CODE_901);
        AssertUtil.isTrue((checkAdmin && !infoDto.getAdmin()), CommonErrorEnum.CODE_404);
    }
}
